const { conn } = require('../gather/mongo');
// 获取聊天记录列表
exports.getopenList = async (req, res) => {
    let { UserId } = req.query;
    const sql = `SELECT * FROM msg_list where user_id = '${UserId}'`;
    conn.query(sql, async (err, result) => {
        if (err) {
            res.json({
                code: 500,
                msg: '查询失败'
            })
        } else {
            getallread(result)
        }
    })
    const getallread = async (result) => {
        let allunread = 0;
        if (result.length !== 0) {
            await result.forEach((item, index) => {
                const sql1 = `SELECT COUNT(*) FROM msg_data_list where send_id = '${item.that_id}' and accept_id = ${item.user_id} and read_state = 0`;
                conn.query(sql1, (err, result1) => {
                    if (err) return
                    const sql2 = `UPDATE msg_list SET unread = ${result1[0]['COUNT(*)']} WHERE that_id = ${item.that_id} and user_id = ${item.user_id}`
                    conn.query(sql2, (err, result2) => {
                        if (err) {
                            console.log(err);
                            res.json({
                                code: 500,
                                msg: '查询失败'
                            })
                        } else {
                            allunread = allunread + result1[0]['COUNT(*)'];
                            if (index == result.length - 1) {
                                conn.query(sql, (err, result4) => {
                                    console.log(result4);
                                    if (err) {
                                        console.log(err);
                                        res.json({
                                            code: 500,
                                            msg: '查询失败'
                                        })
                                    } else {
                                        res.json({
                                            code: 200,
                                            msg: '查询成功',
                                            data: result4,
                                            allunread: allunread
                                        })
                                    }
                                })
                            }
                        }
                    })
                })
            })
        } else {
            res.json({
                code: 200,
                msg: '暂无数据',
            })
        }
    }
}
// 获取聊天信息
exports.getchatcontent = (req, res) => {
    let { UserId, ChatId } = req.query;
    const sql = `SELECT * FROM msg_data_list where send_id = '${UserId}' and accept_id =${ChatId} or send_id = '${ChatId}' and accept_id =${UserId}`;
    conn.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                msg: '查询失败'
            })
        } else {
            res.json({
                code: 200,
                msg: '查询成功',
                data: result
            })
        }
    })
}

// 发送消息
exports.sendMsg = (req, res) => {
    let { UserId, ChatId, Content } = req.body
    const sql1 = `SELECT * FROM msg_list where that_id = ${UserId} and user_id = ${ChatId}`
    const getchatcontent = () => {
        conn.query(sql1, (err, result) => {
            if (err) {
            } else {
                if (result.length == 0) {
                    getinfo()
                } else {
                    updataLeastMsg()
                }
            }
        })
    }
    getchatcontent()
    // 获取信息
    const getinfo = () => {
        let { UserId, ChatId, Content } = req.body
        const sql = `SELECT * FROM user_info where id = ${UserId}`
        conn.query(sql, (err, result1) => {
            if (err) {
            } else {
                getFriendNotes(result1)
            }
        })
    }
    // 找到对好友的备注
    const getFriendNotes = (result1) => {
        const sql = `SELECT friend_notes FROM  friend_list where user_id = ${ChatId} and that_id = ${UserId}`
        conn.query(sql, (err, result) => {
            if (err) {
            } else {
                putchatlist(result1, result)
            }
        })
    }
    // 插入聊天历史记录
    const putchatlist = (result1, r2) => {
        let { UserId, ChatId, Content } = req.body
        const sql2 = `INSERT INTO msg_list (user_id,that_id,open_state,that_avater,that_nickname,that_username,that_notes) VALUES ('${ChatId}','${UserId}',0,'${result1[0].avatar}','${result1[0].nickname}','${result1[0].username}','${r2[0].friend_notes}')`
        conn.query(sql2, (err, result) => {
            if (err) {
            } else {
                updataLeastMsg()
            }
        })
    }
    // 更新最后一条数据
    const updataLeastMsg = () => {
        let { UserId, ChatId, Content } = req.body
        const sql3 = `UPDATE msg_list SET least_msg = '${Content}' WHERE that_id = ${UserId} and user_id = ${ChatId} or that_id = ${ChatId} and user_id = ${UserId}`
        conn.query(sql3, (err, result1) => {
            if (err) {
                console.log(err);
            } else {
                putchatcontent()
            }
        })
    }
    // 获取聊天记录 插入数据
    const putchatcontent = () => {
        let { UserId, ChatId, Content } = req.body
        const sql1 = `SELECT * FROM msg_list where that_id = ${UserId} and user_id = ${ChatId}`
        conn.query(sql1, (err, result) => {
            if (err) {
            } else {
                let sql = ''
                if (result[0]['open_state'] == 1) {
                    sql = `INSERT INTO msg_data_list (send_id,accept_id,send_content,send_time,read_state) VALUES ('${UserId}','${ChatId}','${Content}',now(),1)`
                } else {
                    sql = `INSERT INTO msg_data_list (send_id,accept_id,send_content,send_time) VALUES ('${UserId}','${ChatId}','${Content}',now())`
                }
                conn.query(sql, (err, result) => {
                    if (err) {
                        res.json({
                            code: 500,
                            msg: '发送失败'
                        })
                    } else {
                        res.json({
                            code: 200,
                            msg: '发送成功'
                        })
                    }
                })
            }
        })
    }

}
// 打开聊天 去除未读
exports.removeUnread = (req, res) => {
    let { UserId, ChatId, OpenId } = req.body
    const sql1 = `UPDATE msg_list SET open_state = 1 WHERE that_id = ${ChatId} and user_id = ${UserId}`
    conn.query(sql1, (err, result) => {
        if (err) {
        } else {
            const sql = `UPDATE msg_data_list SET read_state = 1 WHERE send_id = ${ChatId} and accept_id = ${UserId}`
            conn.query(sql, (err, result) => {
                if (err) {
                } else {
                    res.json({
                        code: 200,
                        msg: '去除未读成功',
                        data: result
                    })
                }
            })
        }
    })
}
// 设置打开的状态
exports.changeChatState = (req, res) => {
    let { UserId, ChatId } = req.body
    if (ChatId == -1) {
        const sql = `UPDATE  msg_list SET open_state = 0 where user_id = ${UserId}`
        conn.query(sql, (err, result) => {
            if (err) {
            } else {
                res.json({
                    code: 200,
                    msg: '隐藏成功'
                })
            }
        })
    } else {
        const sql = `UPDATE  msg_list SET open_state = 0 where user_id = ${UserId}`
        conn.query(sql, (err, result) => {
            if (err) {
            } else {
                const sql1 = `UPDATE msg_list SET open_state = 1 WHERE that_id = ${ChatId} and user_id = ${UserId}`
                conn.query(sql1, (err, result) => {
                    if (err) {
                    } else {
                        res.json({
                            code: 200,
                            msg: '隐藏成功'
                        })
                    }
                })
            }
        })
    }

}
// 获取好友分组列表
exports.getFriendgroupList = (req, res) => {
    let { UserId } = req.query
    // 获取该好友分组下的好友
    function getFriend(GroupId) {
        return new Promise((resolve, reject) => {
            const sql = `SELECT COUNT(*) FROM friend_list where group_id = ${GroupId}`
            conn.query(sql, (err, result) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(result)
                }
            })
        })
    }
    const sql = `SELECT * FROM group_list where user_id = ${UserId} `
    conn.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                msg: '查询失败'
            })
        } else {
            let res1 = []
            result.forEach(async (item, index) => {
                let ress = await getFriend(item.group_id)
                res1.push(ress[0]['COUNT(*)'])
                if (index == result.length - 1) {
                    let okres = result.map((item, index) => {
                        return {
                            ...item,
                            friendNum: res1[index]
                        }
                    })
                    res.json({
                        code: 200,
                        msg: '查询成功',
                        data: okres
                    })
                }
            })

        }
    })


}

// 获取好友列表
exports.getFriendList = (req, res) => {
    let { UserId, GroupId } = req.body
    const sql = `SELECT * FROM friend_list where user_id = ${UserId} AND group_id = ${GroupId}`
    conn.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                msg: '查询失败'
            })
        } else {
            res.json({
                code: 200,
                msg: '查询成功',
                data: result
            })
        }
    })
}
// 双击好友或者点击发消息 跳到聊天记录 需要添加聊天记录
exports.addChatRecord = (req, res) => {
    let { UserId, ChatId } = req.body
    const sql = `SELECT * FROM user_info where id = ${ChatId}`
    conn.query(sql, (err, result1) => {
        if (err) {
        } else {
            getFriend(result1)
        }
    })
    function getFriend(result1) {
        const sql = `SELECT friend_notes FROM  friend_list where user_id = ${UserId} and that_id = ${ChatId}`
        conn.query(sql, (err, result) => {
            if (err) {
                console.log(err);
            } else {
                const sql1 = `SELECT * FROM msg_list where user_id = ${UserId} and that_id = ${ChatId}`
                conn.query(sql1, (err, result3) => {
                    if (err) {
                        console.log(err);
                    } else {
                        if (result3.length == 0) {
                            const sql2 = `INSERT INTO msg_list (user_id,that_id,open_state,that_avater,that_nickname,that_username,that_notes) VALUES ('${UserId}','${ChatId}',0,'${result1[0].avatar}','${result1[0].nickname}','${result1[0].username}','${result[0].friend_notes}')`
                            conn.query(sql2, (err, result) => {
                                if (err) {
                                } else {
                                    res.send({
                                        code: 200,
                                        msg: '添加聊天记录成功',
                                    })
                                }
                            })
                        } else {
                            res.send({
                                code: 400,
                                msg: '存在该聊天记录',
                            })
                        }
                    }
                })
            }
        })
    }
}
// 搜索好友
exports.searchFriend = (req, res) => {
    let { UserId, search } = req.body
    const sql = `SELECT * FROM user_info where id!=${UserId} and (username LIKE '%${search}%' OR nickname LIKE '%${search}%')`
    conn.query(sql, (err, result) => {
        if (err) {
            res.json()
        } else {
            let res1 = []
            result.forEach(async (item, index) => {
                let ress = await getFriend(item.id)
                res1.push(ress)
                if (index == result.length - 1) {
                    let okarr = result.map((item, index) => {
                        return {
                            avatar: item.avatar,
                            nickname: item.nickname,
                            username: item.username,
                            that_id: item.id,
                            friendState: res1[index]
                        }
                    })
                    res.json({
                        code: 200,
                        msg: '查询成功',
                        data: okarr
                    })
                }
            })
        }
    })
    // 查找有没有该好友
    function getFriend(id) {
        return new Promise((resolve, reject) => {
            const sql = `SELECT * FROM friend_list where user_id = ${UserId} and that_id = ${id}`
            conn.query(sql, (err, result) => {
                if (result.length == 0) {
                    resolve(0)
                } else {
                    resolve(1)
                }
            })
        })
    }
}
// 添加好友
exports.addfriend = (req, res) => {
    const { UserId, ThatId, GroupId, appmsg, notes } = req.body
    // 获取双方信息
    const sql1 = `SELECT * FROM user_info where id = ${UserId} or id = ${ThatId}`
    conn.query(sql1, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                msg: '查询失败'
            })
        } else {
            testapplication(result)
        }
    })
    // 出入到聊天申请中
    function putapplication(result1) {
        let userinfo = result1.find(item => item.id == UserId)
        let thatinfo = result1.find(item => item.id == ThatId)
        const sq1 = `SELECT app_open from user_info where id = ${ThatId}`
        conn.query(sq1, (err, result3) => {
            if (err) {
                console.log(err);
                res.json({
                    code: 500,
                    msg: '添加失败'
                })
            } else {
                console.log(result3);
                let sql1 = ''
                if (result3[0].app_open == 1) {
                    sql1 = `INSERT INTO application_list (that_id,user_id,application_state,that_nickname,that_username,that_avatar,that_notes,group_id,application_msg,create_time,read_state) VALUES 
                ('${ThatId}','${UserId}',3,'${thatinfo.nickname}','${thatinfo.username}','${thatinfo.avatar}','${notes}',${GroupId},'${appmsg}',now(),1),
                ('${UserId}','${ThatId}',1,'${userinfo.nickname}','${userinfo.username}','${userinfo.avatar}','',0,'',now(),1)`
                } else {
                    sql1 = `INSERT INTO application_list (that_id,user_id,application_state,that_nickname,that_username,that_avatar,that_notes,group_id,application_msg,create_time,read_state) VALUES 
                ('${ThatId}','${UserId}',3,'${thatinfo.nickname}','${thatinfo.username}','${thatinfo.avatar}','${notes}',${GroupId},'${appmsg}',now(),1),
                ('${UserId}','${ThatId}',1,'${userinfo.nickname}','${userinfo.username}','${userinfo.avatar}','',0,'',now(),0)`
                }
                conn.query(sql1, (err, result) => {
                    if (err) {
                        console.log(err);
                        res.json({
                            code: 500,
                            msg: '添加失败'
                        })
                    } else {
                        res.json({
                            code: 200,
                            msg: '添加成功'
                        })
                    }
                })
            }
        })

    }
    // 判断申请列表中有没有该请求
    function testapplication(result) {
        const sql = `SELECT * FROM application_list where user_id = ${UserId} and that_id = ${ThatId}`
        conn.query(sql, (err, result2) => {
            if (err) {
                res.json({
                    code: 500,
                    msg: '查询失败'
                })
            } else {
                if (result2.length == 0) {
                    putapplication(result)
                } else {
                    const sql1 = `UPDATE application_list set application_state = 3,that_notes='${notes}',group_id=${GroupId},application_msg='${appmsg}',create_time=now() where user_id = ${UserId} and that_id = ${ThatId}`
                    conn.query(sql1, (err, result3) => {
                        if (err) {
                            console.log(err);
                            res.json({
                                code: 500,
                                msg: '更新失败'
                            })
                        } else {
                            const sql2 = `UPDATE application_list set read_state = 0 where user_id = ${ThatId} and that_id = ${UserId}`
                            conn.query(sql2, (err, result3) => {
                                if (err) {
                                    console.log(err);
                                    res.json({
                                        code: 500,
                                        msg: '更新失败'
                                    })
                                } else {
                                    res.json({
                                        code: 200,
                                        msg: '更新成功'
                                    })
                                }
                            })
                        }
                    })

                }
            }
        })
    }
}
// 获取好友申请信息列表
exports.getapplicationlist = (req, res) => {
    const { UserId } = req.body
    const sql = `SELECT * FROM application_list where user_id = ${UserId}`
    conn.query(sql, (err, result) => {
        if (err) {
            console.log(err);
            res.json({
                code: 500,
                msg: '查询失败'
            })
        } else {
            getunread(result)
        }
    })
    // 找到好友信息未读的信息
    function getunread(result) {
        const sql = `SELECT COUNT(*) FROM application_list where user_id = ${UserId} and read_state = 0`
        conn.query(sql, (err, result2) => {
            if (err) {
                console.log(err);
                res.json({
                    code: 500,
                    msg: '查询失败'
                })
            } else {
                res.json({


                    code: 200,
                    msg: '查询成功',
                    data: result,
                    unread: result2[0]['COUNT(*)']
                })
            }

        })
    }
}
// 审批好友申请
exports.approval = (req, res) => {
    const { UserId, ThatId, state, GroupId } = req.body
    if (state == 1) {
        const sql = `UPDATE application_list SET 
        application_state = CASE 
        WHEN user_id =${ThatId} AND that_id = ${UserId} THEN 5 
        WHEN user_id =${UserId} AND that_id = ${ThatId} THEN 2 
        ELSE application_state END, 
        create_time = CASE 
        WHEN user_id = ${ThatId} AND that_id = ${UserId} THEN now() 
        WHEN user_id = ${UserId} AND that_id = ${ThatId} THEN now() 
        ELSE create_time END,
        group_id =CASE
        WHEN user_id =${UserId} AND that_id = ${ThatId} THEN ${GroupId} 
        ELSE group_id END
        WHERE user_id IN (${ThatId},${UserId}) AND that_id IN (${UserId},${ThatId})`
        conn.query(sql, (err, result) => {
            if (err) return
            getapplication()
        })
    } else {
        const sql = `UPDATE application_list SET 
        application_state = CASE 
        WHEN user_id =${ThatId} AND that_id = ${UserId} THEN 0 
        WHEN user_id =${UserId} AND that_id = ${ThatId} THEN 4 
        ELSE application_state END, 
        create_time = CASE 
        WHEN user_id = ${ThatId} AND that_id = ${UserId} THEN now() 
        WHEN user_id = ${UserId} AND that_id = ${ThatId} THEN now() 
        ELSE create_time END 
        WHERE user_id IN (${ThatId},${UserId}) AND that_id IN (${UserId},${ThatId})`
        conn.query(sql, (err, result) => {
            if (err) return
            res.json({
                code: 200,
                msg: '审批成功'
            })
        })
    }
    // 如果同意生成两条好友
    function createFriend(r1, r2) {
        let userinfo = r2.find(item => item.id == UserId)
        let userapp = r1.find(item => item.that_id == UserId)
        let thatinfo = r2.find(item => item.id == ThatId)
        // let thatapp = r1.find(item => item.that_id == ThatId)
        const sql = `INSERT INTO friend_list (friend_nickname,friend_avatar,friend_signature,that_id,user_id,group_id,friend_username,friend_age,friend_sex,friend_notes) VALUES 
        ('${userinfo.nickname}','${userinfo.avatar}','${userinfo.signature}',${UserId},${ThatId},${userapp.group_id},'${userinfo.username}',${userinfo.age},'${userinfo.sex}','${userapp.that_notes}'),
        ('${thatinfo.nickname}','${thatinfo.avatar}','${thatinfo.signature}',${ThatId},${UserId},${GroupId},'${thatinfo.username}',${thatinfo.age},'${thatinfo.sex}','')`
        conn.query(sql, (err, result) => {
            if (err) {
                console.log(err);
                res.json({
                    code: 500,
                    msg: '添加失败'
                })
            } else {
                res.json({
                    code: 200,
                    msg: '添加成功'
                })
            }
        })
    }
    // 获取到该两个人的信息
    function getinfo(result) {
        const sql1 = `SELECT * FROM user_info where id = ${UserId} or id = ${ThatId}`
        conn.query(sql1, (err, result1) => {
            if (err) {
                res.json({
                    code: 500,
                    msg: '查询失败'
                })
            } else {
                createFriend(result, result1)
            }
        })
    }
    // 获取这两个申请信息
    function getapplication() {
        const sql2 = `SELECT * FROM application_list where user_id = ${UserId} and that_id = ${ThatId} or user_id = ${ThatId} and that_id = ${UserId}`
        conn.query(sql2, (err, result2) => {
            if (err) {
                res.json({
                    code: 500,
                    msg: '查询失败'
                })
            } else {
                console.log();
                getinfo(result2)
            }
        })
    }
}
// 改变好友申请的阅读状态
exports.changeApplicationState = (req, res) => {
    const { UserId } = req.body
    const sql = `UPDATE application_list SET read_state = 1 WHERE user_id = ${UserId}`
    conn.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                msg: '修改失败'
            })
        } else {
            res.json({
                code: 200,
                msg: '修改成功'
            })
        }
    })
}
// 判断用户好友申请信息页面是否打开
exports.checkApplication = (req, res) => {
    const { UserId, state } = req.body
    const sql = `UPDATE user_info set app_open = ${state}  where id = ${UserId}`
    conn.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
            })
        } else {
            res.json({
                code: 200,
                msg: '修改成功'
            })
        }
    })
}
// 修改好友备注
exports.changeFriendNotes = (req, res) => {
    const { UserId, ThatId, notes } = req.body
    const sql = `UPDATE friend_list SET friend_notes = '${notes}' WHERE user_id = ${UserId} and that_id = ${ThatId}`
    conn.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
            })
        } else {
            changeChatNotes()
        }
    })
    // 修改聊天记录的备注名
    function changeChatNotes() {
        const sql = `UPDATE msg_list SET that_notes = '${notes}' WHERE user_id = ${UserId} and that_id = ${ThatId}`
        conn.query(sql, (err, result) => {
            if (err) {
                res.json({
                    code: 500,
                })
            } else {
                res.json({
                    code: 200,
                    msg: '修改成功'
                })
            }
        })
    }
}
// 改变好友的分组
exports.changeGroup = (req, res) => {
    let { UserId, ThatId, GroupId } = req.body
    let sql = `update friend_list set group_id = ${GroupId} where user_id = ${UserId} AND that_id = ${ThatId}`
    conn.query(sql, (err, result) => {
        if (err) {
            res.json({
                code: 500,
            })
        } else {
            res.json({
                code: 200,
                msg: '修改成功'
            })
        }
    })
}